﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Runtime.CompilerServices;
using shop.Model;
using CommonTools;
using Newtonsoft.Json.Linq;
using MD5 = CommonTools.MD5;
using System.Data.SqlClient;
using System.Linq;

namespace shop.Bll
{
    public class UserBll: CommonTools.IUserBll
    {
        /// <summary> 当前登录用户 </summary>
        public static JUser CurrentUser
        {
            set
            {
                _currentUser = value;
                //引发事件
                OnUserChanged(value);
            }

            get => _currentUser;
        }

        private static JUser _currentUser;


        #region 方法

        public IEnumerable<IUser> GetAllUser()
        {
            //var user = DB.FSql.Select<JUser>()
            //    .Where(s => s.Isdel == false && s.Isrole == false)
            //    .ToList();

            //return user;

            var list = DB.FSql.Select<JUser, JUserRole, JUser>()
               .LeftJoin((a, b, c) => a.DocID == b.CodeID)
               .LeftJoin((a, b, c) => b.RoleID == c.DocID && c.Isdel == false)
               .Where((a, b, c) => a.Isdel == false)
               .ToList((a, b, c) => new
               {
                   a.Name,
                   Code = a.DocID,
                   a.Dept,
                   a.EmpID,
                   a.SafeMode,
                   roleName = c.Name
               });


            var res = list.GroupBy(a => new { a.Name, a.Code, a.Dept, a.EmpID, a.SafeMode })
                .Select(a => new JUser()
                {
                    Name = a.Key.Name,
                    Code = a.Key.Code,
                    Dept = a.Key.Dept,
                    EmpID = a.Key.EmpID,
                    SafeMode = a.Key.SafeMode,
                    Role = a.Select(c => c.roleName).Aggregate((c, n) => c + "," + n),
                })
                .ToList();

            return res;

        }


        public IEnumerable<IUser> GetAllRole()
        {
            return DB.FSql.Select<JUser>()
                .Where(a => a.Isdel == false && a.Isrole == true)
                .ToList();
        }


        /// <summary>
        /// 删除用户名
        /// </summary> 
        public bool Delete(IUser user, out string err)
        {
            if (user is JUser ju)
            {
                ju.Isdel = true;
                //先删除权限
                DeleteRights(user, out err);

                DB.FSql.Update<JUser>()
                    .Where(ju)
                    .Set(a => a.Isdel, true)
                    .ExecuteAffrows();

            }

            err = "";
            return true;
        }


        /// <summary>
        /// 查询用户
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public IUser GetUser(string name)
        {
//            string cmd = @"SELECT user2.DocID, user2.Name, role.Name as role,user2.Password, user2.SafeMode, user2.EmpID, user2.Dept, user2.Biller, user2.BillerDate
//FROM dbo.JUser user2
//left join dbo.JUserRole ur on user2.isdel=0 and user2.docid=ur.codeid and user2.isrole=0 
//left join dbo.JUser role on role.isdel=0 and role.isrole=1 and ur.roleid=role.DocID
//where user2.Name=@name ";


//            DataTable dt = DB.FSql.Ado.ExecuteDataTable(CommandType.Text, cmd, new SqlParameter("@name", name));
//            if (dt.Rows.Count > 0)
//            {
//                return new JUser()
//                {
//                    Name = dt.Rows[0]["Name"].ToString(),
//                    DocID = dt.Rows[0]["DocID"].IsNull(0),
//                    Role = dt.Rows[0]["role"].IsNull(),
//                    Password = dt.Rows[0]["Password"].IsNull(),
//                };
//            }
//            else
//            {
//                return null;
//            }


            var res = DB.FSql.Select<JUser, JUserRole, JUser>()
                .LeftJoin((a, b, c) => a.DocID == b.CodeID && a.Isrole == false)
                .LeftJoin((a, b, c) => c.Isdel == false && c.Isrole == true && b.RoleID == c.DocID)
                .Where((a, b, c) => a.Isdel == false && a.Name == name)
                .ToOne((a,b,c) => new JUser() 
                { 
                    Name= a.Name, DocID=a.DocID, Role=c.Name, Password= a.Password,
                });

            return res;
    
        }

        /// <summary> 获取用户 </summary>
        public JUser GetUserById(int id)
        {
            return DB.FSql.Select<JUser>()
                .Where(s => s.DocID == id && s.Isdel == false && s.Isrole == false)
                .ToOne();
        }

        /// <summary>
        /// 查询角色是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool CheckRole(string name)
        {
            return DB.FSql.Select<JUser>()
                .Any(s => s.Name == name && s.Isdel == false && s.Isrole == true);
        }

        /// <summary>
        /// 查询角色
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public JUser GetRole(string name)
        {
            return DB.FSql.Select<JUser>()
                .Where(s => s.Name == name && s.Isdel == false && s.Isrole == true)
                .ToOne();

        }


        /// <summary>
        /// 添加用户EF
        /// </summary>
        /// <param name="user"></param>
        /// <param name="err"></param>
        /// <returns></returns>
        public bool Add(JUser user, out string err)
        {
            user.Name = user.Name.Trim();

            //检查
            if (CheckRepeat(user.Name) == true)
            {
                err = "已经相同姓名用户: \"" + user.Name + "\"";
                return false;
            }
            else
            {
                err = "";                
                var id = DB.FSql.Insert<JUser>(user).ExecuteIdentity();
                user.DocID = (int)id;


                return true;
            }

        }


        /// <summary> 就,检查是否已经有这个用户名 </summary>
        public bool CheckRepeat(string name)
        {
            return DB.FSql.Select<JUser>().Any(a => a.Name == name && a.Isdel == false);
        }



        /// <summary> 就,检查是否已经有这个用户名的角色 </summary>
        public static bool CheckRepeatRole(int code)
        {
            return DB.FSql.Select<JUserRole>().Any(r => r.CodeID == code);
        }



        /// <summary>
        /// 添加角色
        /// </summary>  
        public bool AddRole(JUserRole newrole, out string err)
        {
            err = "";
            //检查
            if (CheckRepeatRole(newrole.CodeID) == true)
            {
                JUserRole role = DB.FSql.Select<JUserRole>().Where(r => r.CodeID == newrole.CodeID).ToOne();

                role.RoleID = newrole.RoleID;
                
                DB.FSql.Update<JUserRole>()
                 .SetSource(role)
                 .ExecuteAffrows();


                return true;
            }
            else
            {                
                var id = DB.FSql.Insert<JUserRole>(newrole).ExecuteIdentity();
                newrole.ID = (int)id;

                return true;
            }

        }


        /// <summary>
        /// 给用户添加/删除 角色
        /// </summary> 
        public bool AddRole(JUserRole newrole, bool addOrDelete,out string err)
        {
            err = "";
            //
            if (addOrDelete == false)
            {
                //移除角色

                DB.FSql.Delete<JUserRole>()
                .Where(u => u.CodeID == newrole.CodeID && u.RoleID == newrole.RoleID)
                .ExecuteAffrows();

                return true;
            }
            else
            {
                //添加角色
                var id = DB.FSql.Insert<JUserRole>(newrole).ExecuteIdentity();
                newrole.ID = (int)id;

                return true;
            }
        }

        public IEnumerable<IJUserRole> GetUserRole(int userId)
        {
            return DB.FSql.Select<JUserRole>().Where(r => r.CodeID == userId).ToList();
        }



        /// <summary>
        /// 查询所有用户名
        /// </summary>
        /// <returns></returns>
        public List<JUser> QueryAll(bool isrole)
        {
            //string cmd = "SELECT us.DocID, us.Name, ISNULL(ro.Name,'') as role,us.Password, us.SafeMode, us.EmpID, us.Dept, us.Biller, us.BillerDate  "
            //            + "FROM dbo.JUser AS us "
            //            + "LEFT join dbo.JUserRole ur on us.isdel = 0 and us.docid = ur.codeid and us.isrole = 0"
            //            + "LEFT join dbo.JUser ro ON ro.isdel = 0 and ro.isrole = 1 and ur.roleid = ro.DocID "
            //            + "where us.isdel = 0 and us.isrole=0 and ISNULL(ro.isdel,0)= 0";

            //DataTable dt = DB.FSql.Ado.ExecuteDataTable(CommandType.Text, cmd);

            //List<JUser> list = new List<JUser>();
            //foreach (DataRow row in dt.Rows)
            //{
            //    list.Add(new JUser()
            //    {
            //        Name = row["Name"].ToString(),
            //        DocID = row["DocID"].IsNull(0),
            //        Role = row["role"].IsNull(),
            //    });
            //}

            //return list;

            var res = DB.FSql.Select<JUser, JUserRole, JUser>()
                .LeftJoin((a, b, c) => a.DocID == b.CodeID && a.Isrole == false)
                .LeftJoin((a, b, c) => c.Isdel == false && c.Isrole == true && b.RoleID == c.DocID)
                .Where((a, b, c) => a.Isdel == false && a.Isrole == false && (c == null || c.Isdel == false && c.Isdel == null))
                .ToList((a, b, c) => new JUser()
                {
                    Name = a.Name,
                    DocID = a.DocID,
                    Role = c.Name,
                });

            return res;
        }


        /// <summary>
        /// 尝试登录
        /// 登陆成功后, 修改当前用户UserBll.CurrentUser, 刷新用户的所有权限列表
        /// </summary>
        /// <param name="user">用户</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        public bool TryLogin(JUser user, string pwd)
        {
            string md5 = MD5.MD5code(pwd);
             
            var u = new UserBll().GetUser(user.Name) as JUser;
            if (u == null) 
            {
                user.Permissions = new List<string>();
                return false;
            }
            else if ((string.IsNullOrEmpty(u.Password.Trim()) && string.IsNullOrEmpty(pwd.Trim()))
                     || (string.Equals(md5, u.Password, StringComparison.OrdinalIgnoreCase)))
            {
                //检查密码: 密码可以同时是空,null,  MD5不区分大小写
                //密码正确

                user.DocID = u.DocID;

                //登陆后,记录ip,mac地址
                KeyValuePair<string, string> ipmac = CommonTools.HardwareHelper.GetAddress();
                string computer = CommonTools.HardwareHelper.GetComputerName();
                user.Ip = ipmac.Key;        // ip地址
                user.Mac = ipmac.Value;     // mac地址
                user.ComputerInfo= computer + "," + ipmac.Key + "," + ipmac.Value;  //计算机名,ip地址,mac地址

                user.Role = "";
                
                //登陆成功后, 刷新用户的所有权限列表
                user.Permissions = GetUserRights(user);

                //用户配置文件
                user.Profile = GetUserProfile(user) ?? new JUserProfile() ;
                
                UserBll.CurrentUser = user;

                return true;
            }
            else
            {
                user.Permissions = new List<string>();
                return false;
            }
        }



        /// <summary>
        /// 获取用户所有权限
        /// </summary>
        public List<string> GetUserRights(JUser user)
        {
            var list = DB.FSql.Select<JUserRight>()
           .Where(a => a.UserId == user.Code).ToList(a => a.RightCode);


            //管理员权限
            if (list.Contains("110") == true)
            {
                list.Clear();
                list.Add("110");
            }

            //查询用户的角色权限
            var list2 = DB.FSql.Select<JUserRole, JUserRight>()
            .InnerJoin((a, b) => a.RoleID == b.UserId)
            .Where((a, b) => a.CodeID == user.Code)
            .ToList((a, b) => b.RightCode);

            list.AddRange(list2);

            return list;

        }



        /// <summary> 检查权限 </summary>
        public static bool CheckRight(string qx)
        {
            if (UserBll.CurrentUser == null)
                return false;
            
            //管理员
            if (Bll.UserBll.CurrentUser.Permissions.Contains("110"))
                return true;

            //检查
            return Bll.UserBll.CurrentUser.Permissions.Contains(qx);
        }

        /// <summary>
        /// 检查指定用户的权限
        /// </summary>
        /// <param name="right"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public static bool CheckRight(string right, JUser user)
        {
            var userId = user.Code;

            //先检查用户的权限, 再检查用户对应角色的权限
            if (!DB.FSql.Select<JUserRight>().Any(s => s.UserId == userId && (s.RightCode == right || s.RightCode == "110")))
            {
                var res = DB.FSql.Select<JUserRole, JUserRight>()
                    .InnerJoin((a, b) => a.RoleID == b.UserId)
                    .Where((a, b) => a.CodeID == userId && (b.RightCode == right || b.RightCode == "110"))
                    .Any();

                return res;
            }

            return true;

        }


        public static bool ChangePassword(string name, string oldpwd, string newpwd, string repeatpwd)
        {
            string md5 = MD5.MD5code(oldpwd);

            var u = new UserBll().GetUser(name) as JUser;
            if (u == null)
            {
                return false;
            }
            else if ((string.IsNullOrEmpty(u.Password.Trim()) && string.IsNullOrEmpty(oldpwd.Trim()))
                     || (string.Equals(md5, u.Password, StringComparison.OrdinalIgnoreCase)))
            {
                //检查密码: 密码可以同时是空,null,  MD5不区分大小写
                //密码正确

                string newmd5 = MD5.MD5code(newpwd);
                var u1 = DB.FSql.Select<JUser>().Where(a => a.Name == name && a.Isdel == false).ToOne();
                if (u1 != null)
                {
                    DB.FSql.Update<JUser>()
                    .SetSource(u1)
                    .Set(a => a.Password, newmd5)
                    .ExecuteAffrows();
                }


                return true;

            }
            else
            {
                return false;
            }

        }



        #endregion


        #region 更换用户事件

        /// <summary>
        /// 声明事件,
        /// 窗体中的用法:
        /// BLL.UserBll.UserChanged += () => PermissionTool.CheckPermission(this);  //更换用户后重新检查权限
        /// </summary>
        public static event Action UserChanged;


        /// <summary>
        /// 触发事件, 登陆时使用这个
        /// </summary>
        public static void OnUserChanged(JUser user)
        {
            UserChanged?.Invoke();
        }



        #endregion



        public IEnumerable<IJRight> GetAllRights()
        {
            var va = DB.FSql.Select<JRight>().Where(s => s.Code.Length < 6).OrderBy(s => s.Code).ToList();

            List<JRight> list = new List<JRight>();
            list.AddRange(va);
            return list;
        }



        #region 用户配置文件


        public static JUserProfile GetUserProfile(JUser user)
        { 

            var res = DB.FSql.Select<JUser>()
               .Where(a => a.DocID == user.DocID && a.Isdel == false)
               .ToOne();

            var json= res?.ProfileJson;

            if (string.IsNullOrEmpty(json))
            {
                return null;
            }
            else
            {
                return JObject.Parse(json).ToObject<JUserProfile>();
            }
        }

        public static bool ModifyUserProfile(JUser user, JUserProfile profile, out string  err)
        {
            err = "";

            string json = profile == null ? "" : JObject.FromObject(profile).ToString();

            DB.FSql.Update<JUser>()
              .Set(a => a.ProfileJson, json)
              .Where(a => a.DocID == user.DocID && a.Isdel == false)
              .ExecuteAffrows();

            return true;
        }


        /// <summary> 设置用户是否业务员 </summary>
        public static void SetSaler(string name, bool issaler)
        {
            DB.FSql.Update<JUser>()
                .Where(a => a.Isdel == false && a.Name == name)
                .Set(a => a.IsSaler, issaler)
                .ExecuteAffrows();
        }



        #endregion




        public IEnumerable<IJRight> GetItemRights(string code)
        {
            var list = DB.FSql.Select<JRight>().Where(a => a.CodeLevel == 3 && a.Code.StartsWith(code))
             .ToList();

            return list;
        }

        /// <summary> 查询用户在一个模块下有什么权限 </summary>
        public IEnumerable<IJUserRight> GetUserRight(string code, int userId)
        {
            var rights = DB.FSql.Select<JUserRight>()
                   .Where(a => a.UserId == userId && a.RightCode.StartsWith(code))
                   .ToList();


            //管理员权限
            if (rights.Any(a => a.RightCode == "110") == true)
            {
                rights.Clear();
                rights.Add(new JUserRight() { UserId = userId, RightCode = "110" });
            }

            //查询用户的角色权限
            var list2 = DB.FSql.Select<JUserRole, JUserRight>()
                .InnerJoin((a, b) => a.RoleID == b.UserId)
                .Where((a, b) => a.CodeID == userId && b.RightCode.StartsWith(code) )
                .ToList((a, b) => b);

            rights.AddRange(list2);

            return rights;
        }

        public void AddRight(string right, int userId)
        {
            //检查
            var p = DB.FSql.Select<JUserRight>().FirstOrDefault(a => a.RightCode == right && a.UserId == userId);
            if (p == null)
            {
                JUserRight ps = new JUserRight()
                {
                    UserId = userId,
                    RightCode = right,
                };

                DB.FSql.Insert(ps).ExecuteAffrows();
            }
        }

        public void RemoveRight(string right, int userId)
        {
            DB.FSql.Delete<JUserRight>()
                .Where(a => a.RightCode == right && a.UserId == userId)
                .ExecuteAffrows();
        }

        public bool CopyRight(string userName, string user2Name, out string err)
        {
            var u1 = GetUser(userName);
            var u2 = GetUser(user2Name);
            if (u1 == null)
            {
                err = "没有找到用户: " + userName;
                return false;
            }
            if (u2 == null)
            {
                err = "没有找到用户: " + user2Name;
                return false;
            }


//            var cmd = @"DECLARE @userId			INT,	----添加权限的用户id
//@user2Id		INT		----复制权限的用户id

//INSERT INTO dbo.JUserRight(UserId, RightCode)
//SELECT DISTINCT @userId,JUserRight.RightCode
//FROM dbo.JUserRight 
//LEFT JOIN (SELECT RightCode FROM dbo.JUserRight WHERE UserId=@userId) AS c ON c.RightCode = JUserRight.RightCode
//WHERE UserId=@user2Id AND c.RightCode IS NULL ";

//            SqlParameter[] pr = new SqlParameter[]
//            {
//                new SqlParameter("@userId", SqlDbType.Int) { Value = u1.Code},
//                new SqlParameter("@user2Id", SqlDbType.Int){ Value = u2.Code},
//            };

//            DB.FSql.Ado.ExecuteNonQuery(CommandType.StoredProcedure, cmd, pr);

            DB.FSql.Select<JUserRight, JUserRight>()
                .LeftJoin((a, b) => a.RightCode == b.RightCode && b.UserId == u1.Code)
                .Where((a, b) => a.UserId == u2.Code && (b == null))
                .Distinct()
                .InsertInto(nameof(JUserRight), (a, b) => new JUserRight { UserId = u1.Code, RightCode = a.RightCode });
                
            err = "";
            return true;

        }

        /// <summary> 权限代码 </summary>
        public IEnumerable<dynamic> QueryRightReport()
        {
            var jRightTable = CommonTools.ToolConfig.JRightTable;

            var cmd = $@"SELECT   urs_1.DocId AS UserCode, urs_1.Name AS UserName, ri.level1, ri.level2, ri.Name AS RightName, 
                urs_1.RightCode
FROM      (SELECT   u_1.Name, u_1.UserCode, urs.RightCode, u_1.DocId
                 FROM      (SELECT   DocId AS UserCode, Name, DocId
                                  FROM      dbo.JUser AS u
                                  WHERE   (Isdel = 0) AND (Isrole = 0)
                                  UNION ALL
                                  SELECT   ur.RoleID AS UserCode, u.Name, u.DocId
                                  FROM      dbo.JUser AS u INNER JOIN
                                                  dbo.JUserRole AS ur ON u.DocId = ur.CodeID
                                  WHERE   (u.Isdel = 0) AND (u.Isrole = 0)) AS u_1 INNER JOIN
                                 dbo.JUserRight AS urs ON urs.UserId = u_1.UserCode) AS urs_1 LEFT OUTER JOIN
                    (SELECT   m.Name, l1.level1, l2.level2, m.Code
                     FROM      dbo.{jRightTable} AS m INNER JOIN
                                         (SELECT   Name AS level2, Code AS level2Code
                                          FROM      dbo.{jRightTable} WITH (NOLOCK)
                                          WHERE   (CodeLevel = 2)) AS l2 ON m.Code LIKE l2.level2Code + '%' INNER JOIN
                                         (SELECT   Name AS level1, Code AS level1Code
                                          FROM      dbo.{jRightTable} AS JRights_1 WITH (NOLOCK)
                                          WHERE   (CodeLevel = 1)) AS l1 ON l2.level2Code LIKE l1.level1Code + '%') AS ri ON 
                ri.Code = urs_1.RightCode";

            var dt = DB.FSql.Ado.ExecuteDataTable(CommandType.Text, cmd);
            var list = dt.AsEnumerable()
                .Select(a => new
                {
                    用户代码 = a.Field<int?>("UserCode"),
                    用户名 = a.Field<string>("UserName"),
                    权限代码 = a.Field<string>("RightCode"),
                    一级权限 = a.Field<string>("level1"),
                    二级权限 = a.Field<string>("level2"),
                    权限名称 = a.Field<string>("RightName"),
                })
                .ToList();

            return list;
        }

        /// <summary>  </summary>
        public IEnumerable<dynamic> QueryRoleReport()
        {
            string cmd = @"SELECT u.DocID, u.Name, r.DocID AS RoleId, r.Name AS RoleName 
            FROM dbo.JUser AS u
                INNER JOIN dbo.JUserRole AS ur ON u.DocID = ur.CodeID AND u.Isrole = 0
            INNER JOIN dbo.JUser AS r ON ur.RoleID = r.DocID AND r.Isrole = 1
            where r.Isdel = 0 AND u.Isdel = 0 ";

            DataTable dt = DB.FSql.Ado.ExecuteDataTable(CommandType.Text, cmd);

            var list = dt.AsEnumerable()
                .Select(a => new
                {
                    用户代码 = a.Field<int?>("DocID"),
                    用户名 = a.Field<string>("Name"),
                    角色代码 = a.Field<int?>("RoleId"),
                    角色名称 = a.Field<string>("RoleName"),
                })
                .ToList();

            return list;
        }

        public IUser CreateUser()
        {
            return new JUser() { Isrole = false };
        }

        public IUser CreateRole()
        {
            return new JUser() { Isrole = true };
        }

        public IJUserRole CreateUserRole()
        {
            return new JUserRole();
        }

        public IJRight CreateRight()
        {
            return new JRight();
        }

        public bool Add(IUser user, out string err)
        {
            var ju = user as JUser;

            ju.Name = ju.Name.Trim();

            //检查
            if (CheckRepeat(ju.Name) == true)
            {
                err = "已经相同姓名用户: \"" + ju.Name + "\"";
                return false;
            }
            else
            {
                err = "";
                var id = DB.FSql.Insert(ju).ExecuteIdentity();
                ju.Code = (int)id;

                return true;
            }

        }


        /// <summary> 删除用户所有权限 </summary>
        public bool DeleteRights(IUser user, out string err)
        {
            err = null;

            DeleteUserRights(user as JUser);

            return true;
        }



        public bool SetUserRole(IJUserRole userRole, bool check, out string err)
        {
            err = "";
            //检查
            if (check == false)
            {
                DB.FSql.Delete<JUserRole>()
                    .Where(a => a.CodeID == userRole.CodeID && a.RoleID == userRole.RoleID)
                    .ExecuteAffrows();

                return true;
            }
            else
            {
                var id = DB.FSql.Insert<JUserRole>(userRole as JUserRole).ExecuteIdentity();
                userRole.ID = (int)id;

                return true;
            }
        }


        /// <summary> 删除用户所有权限 </summary>
        public bool DeleteUserRights(JUser user)
        {
            var u = DB.FSql.Select<JUser>().FirstOrDefault(a => a.DocID == user.Code);

            if (u == null)
            {
                return false;
            }
            else
            {

                DB.FSql.Delete<JUserRight>()
                .Where(a => a.UserId == u.Code)
                .ExecuteAffrows();

                DB.FSql.Delete<JUserRole>()
                .Where(a => a.CodeID == u.Code)
                .ExecuteAffrows();

                return true;
            }
        }


        public bool ChangePassword(string name, string oldpwd, string newpwd, string repeatpwd, out string err)
        {
            if (CheckRight("110") == false)
            {
                if (newpwd != repeatpwd)
                {
                    err = "两次输入的密码不一致!";
                    return false;
                }
            }

            string md5 = MD5.MD5code(oldpwd);

            var u = GetUser(name) as JUser;
            if (u == null)
            {
                err = "没有找到指定用户名!";
                return false;
            }
            else if ((string.IsNullOrEmpty(u.Password.Trim()) && string.IsNullOrEmpty(oldpwd.Trim()))
                     || (string.Equals(md5, u.Password, StringComparison.OrdinalIgnoreCase)))
            {
                string newmd5 = MD5.MD5code(newpwd);

                DB.FSql.Update<JUser>()
                    .Where(a => a.Name == name)
                    .Set(a => a.Password, newmd5)
                    .ExecuteAffrows();

                err = null;
                return true;
            }
            else
            {
                err = "原密码不正确!";
                return false;
            }

        }

        public bool ExistsCode(IJRight right)
        {
            return DB.FSql.Select<JRight>().Any(a => a.Code == right.Code && a.ID != right.ID);
        }
    }


}
